package org.example.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.example.DAO.CommentDao;
import org.example.entity.Comment;
import org.example.entity.User;
import org.example.impl.CommentDaoImpl;
import org.example.Util.DataSourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Arrays;

@WebServlet("/add-comment")
public class AddCommentServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(AddCommentServlet.class);
    private CommentDao commentDao;
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init() throws ServletException {
        this.commentDao = new CommentDaoImpl(DataSourceUtil.getDataSource());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(false);

        try {
            // 1. 验证用户登录状态
            if (session == null || session.getAttribute("user") == null) {
                out.print("{\"success\":false,\"message\":\"未登录\",\"code\":401}");
                return;
            }

            // 2. 从JSON请求体中获取参数
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String jsonPayload = buffer.toString();

            if (jsonPayload.isEmpty()) {
                throw new IllegalArgumentException("请求体为空");
            }

            // 解析JSON
            JsonNode jsonNode = objectMapper.readTree(jsonPayload);

            int contentId = jsonNode.get("contentId").asInt();
            String contentType = jsonNode.get("contentType").asText();
            int rating = jsonNode.get("rating").asInt();
            String content = jsonNode.get("content").asText().trim();

            // 3. 参数验证
            if (contentId <= 0) {
                throw new IllegalArgumentException("无效的内容ID");
            }

            if (!contentType.matches("movie|book|music")) {
                throw new IllegalArgumentException("无效的内容类型");
            }

            if (rating < 1 || rating > 5) {
                throw new IllegalArgumentException("评分必须在1-5之间");
            }

            if (content.isEmpty()) {
                throw new IllegalArgumentException("评论内容不能为空");
            }

            // 4. 获取当前用户
            User user = (User) session.getAttribute("user");

            // 5. 创建评论对象
            Comment comment = new Comment();
            comment.setUserId(user.getId());
            comment.setUsername(user.getUsername());
            comment.setContentId(contentId);
            comment.setContentType(contentType);
            comment.setRating(rating);
            comment.setContent(content);
            comment.setCreateTime(new Timestamp(System.currentTimeMillis()));

            // 6. 保存评论
            boolean success = commentDao.addComment(comment);

            // 7. 返回响应
            if (success) {
                session.setAttribute("commentSuccess", "评论提交成功");
                out.print("{\"success\":true,\"message\":\"评论提交成功\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"评论保存失败\"}");
            }

        } catch (IllegalArgumentException e) {
            logger.warn("参数验证失败", e);
            out.print(String.format("{\"success\":false,\"message\":\"%s\",\"code\":400}", e.getMessage()));
        } catch (SQLException e) {
            logger.error("数据库错误", e);
            out.print("{\"success\":false,\"message\":\"数据库错误\",\"code\":500}");
        } catch (Exception e) {
            logger.error("系统错误", e);
            out.print("{\"success\":false,\"message\":\"系统错误\",\"code\":500}");
        } finally {
            out.close();
        }
    }
}